package com.hmall.gateway.filters;

import cn.hutool.core.text.AntPathMatcher;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter , Ordered {
    public static final String AUTH_TOKEN = "Authorization";

    private final JwtTool jwtTool;

    private final AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if(isExcludePath(request.getPath().value())){
            return chain.filter(exchange);
        }
        List<String> strings = request.getHeaders().get(AUTH_TOKEN);
        String token = null;
        if(!CollectionUtils.isEmpty(strings)){
            token = strings.get(0);
        }
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        }catch (Exception e){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        String StrUserId = userId.toString();
        ServerWebExchange newExchange = exchange.mutate()
                .request(builder -> builder.header("userId", StrUserId))
                .build();
        return chain.filter(newExchange);
    }

    private boolean isExcludePath(String value) {
        for(String path:authProperties.getExcludePaths()){
            if(antPathMatcher.match(path,value)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
